import Vue from 'vue'
import store from "../store/index.js"
import config from "../config.js"

/**
 * @param method eg: get|post|put|delete|GET|POST|PUT|DELETE
 * @param path eg: /user/list
 * @param data 请求携带的body参数，json请求方式，传对象
 * @param testData object  测试模式时返回的数据
 * @param success function 成功的回调函数
 * @param fail function 
 * @param complete function 
 * @param showLoading 是否需要遮罩, 默认有
 * @return Promise<object> 
 */
export default function({
	method = "GET",
	path,
	data,
	testData,
	success,
	fail,
	complete,
	showLoading
}) {
	if (config.useTest) { // 是否是测试模式
		Vue.prototype.$msg(`[测试成功] [${method}] apiPath=${path}`)
		if (typeof(testData) == 'function') testData = testData()
		console.log(`[测试成功] [${method}] apiPath=${path} testData: `, testData)
		if (success) success({
			code: 20000,
			msg: "mock:ok",
			data: testData
		})
		return
	}

	if (showLoading == null || showLoading == true) uni.showLoading({
		mask: true
	})
	uni.request({
		method: method,
		url: config.baseUrl + path,
		dataType: 'json', // 请求体类型，会自动转换成json字符串
		data: data, // 请求体，object
		header: {
			"token": uni.getStorageSync("token"),
			"shop-id": uni.getStorageSync("shopId"),
		},
		timeout: 5000,
		success: function(response) {
			if (response.header && (response.header.token || response.header.Token)) {
				console.log("更新token")
				uni.setStorageSync("token",
					response.header.token ? response.header.token : response.header.Token)
			}
			console.log(`[api响应结果] [${method}] apiPath=${path} response: `, response)
			// status为[200,400)之间时才算成功
			if (!(response.statusCode >= 200 && response.statusCode < 300)) {
				Vue.prototype.$msg("服务器异常: " + response.statusCode)
				return
			}

			let res = response.data
			if (res.code >= 0 && res.code < 30000) {
				if (success) success(res)
			} else if (40100 <= res.code && res.code < 40200) {
				uni.removeStorageSync("token")
				store.commit("setUserInfo", {})
				Vue.prototype.$msg('未登录或登录已经过期，请重新登录')
			} else {
				if (fail) fail(res)
				else Vue.prototype.$msg("failed: " + res.msg)
			}
		},
		fail: function(err) {
			console.error("未知异常：", err)
			Vue.prototype.$msg("未知异常: " + JSON.stringify(err))
		},
		complete: function() {
			uni.hideLoading()
			if (complete) complete()
		}
	})
}
